<?php
Yii::import('common.extensions.multimodelform.MultiModelForm');
class ContentController extends FController
{
    public function __construct($id,$module=null) {
        parent::__construct($id,$module);
        $this->menu=array(
            array('label'=>t('Contents Manager','content'), 'url'=>array('/content/admin'),'linkOptions'=>array('class'=>'btn')),
            array('label'=>t('Add New Content','content'), 'url'=>array('/content/create'),'linkOptions'=>array('class'=>'btn')),
        );
    }
    /*
     * Actions
     */
    public function actions()
    {
        return array(
            'toggle' => array(
                'class'=>'bootstrap.actions.TbToggleAction',
                'modelName' => 'Content',
            ),
            'autocomplete' => array(
                'class'=>'common.components.actions.AutoComplete',
                'model_class' => 'Content',
                'field' => 'title',
            )
        );
    }
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{

		$model=new Content;
        $media = new ContentMedia;
        $validatedMembers = array();  //ensure an empty array

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Content']))
		{
            $user = getSession('current_user');

            /**
             * Fix hidden type Multiformmodel
             */
            $postMedia = $_POST['ContentMedia'];
            $refArray = $postMedia['name'];
            foreach($refArray as $key => $val) {
                if(empty($val) && empty($postMedia['url'][$key]) && empty($postMedia['description'][$key])) {
                    unset($_POST['ContentMedia']['name'][$key]);
                    unset($_POST['ContentMedia']['url'][$key]);
                    unset($_POST['ContentMedia']['description'][$key]);
                    unset($_POST['ContentMedia']['type'][$key]);
                }
            }

            $model->attributes=$_POST['Content'];
            /*----------------------Publishing Date-------------------------*/
            if($_POST['Content']['publishing_start'] !='' && $_POST['Content']['publishing_start'] != null){
                $publishing_start_date = CDateTimeParser::parse($_POST['Content']['publishing_start'],app()->locale->getDateFormat('short'));
                $publishing_start_date_time = date('Y-m-d',$publishing_start_date).' '.$_POST['Content']['publishing_start_time'];
                $model->publishing_start = convertTimeZone(date('Y-m-d H:i:s',strtotime($publishing_start_date_time)));
            }
            if($_POST['Content']['publishing_end'] !='' && $_POST['Content']['publishing_end'] != null) {
                $publishing_end_date = CDateTimeParser::parse($_POST['Content']['publishing_end'],app()->locale->getDateFormat('short'));
                $publishing_end_date_time   = date('y-m-d',$publishing_end_date).' '.$_POST['Content']['publishing_end_time'];
                $model->publishing_end = convertTimeZone(date('Y-m-d H:i:s',strtotime($publishing_end_date_time)));
            }

            /*----------------------#Publishing Date-------------------------*/

            /*----------------------Serial bài viết-------------------*/
            if(isset($_POST['Content']['serial']) && is_numeric($_POST['Content']['serial'])){
                $model->serial = Content::getOriginalSerial($_POST['Content']['serial']);
            }
            /*----------------------#Serial bài viết-------------------*/

            /*----------------------Xử lý Active bài viết -------------------*/
            if($_POST['Content']['status'] == 'active') {
                $model->activate_user_id =  $user['id'];
                $model->activate_date = new CDbExpression('UTC_TIMESTAMP()');
            }
            /*----------------------#Xử lý Active bài viết -------------------*/

            /*--------------------- Xử lý ảnh thumbnail -----------------------*/
            $thumbnail_folder = cmsFile()->set($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/');
            $thumbnail_folder_small = cmsFile()->set($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small');
            $thumbnail_folder_medium = cmsFile()->set($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large');
            $thumbnail_folder_large = cmsFile()->set($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium');

            $post_img = $_POST['Content']['image'];
            if($post_img != '') {
                $source = $_SERVER['DOCUMENT_ROOT'].$post_img;
                $file = cmsFile()->set($source);
                if($file->isfile) {
                    if(!$thumbnail_folder->exists) {
                        $thumbnail_folder->CreateDir();
                    }
                    if(!$thumbnail_folder_large->exists) {
                        $thumbnail_folder_large->CreateDir();
                    }
                    if(!$thumbnail_folder_medium->exists) {
                        $thumbnail_folder_medium->CreateDir();
                    }
                    if(!$thumbnail_folder_small->exists){
                        $thumbnail_folder_small->CreateDir();
                    }
                    $basename = $file->basename;
                    $small_width = settings()->get('general','image_thumbnail_small_width');
                    $small_height = settings()->get('general','image_thumbnail_small_height');
                    $medium_width = settings()->get('general','image_thumbnail_medium_width');
                    $medium_height = settings()->get('general','image_thumbnail_medium_height');
                    $large_width = settings()->get('general','image_thumbnail_large_width');
                    $large_height = settings()->get('general','image_thumbnail_large_height');

                    $thumbnail_small = cmsFile()->set($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small/'.$basename);
                    $thumbnail_medium = cmsFile()->set($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium/'.$basename);
                    $thumbnail_large = cmsFile()->set($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large/'.$basename);
                    $image = image($source);
                    if(!$thumbnail_small->exists && !$thumbnail_medium->exists && !$thumbnail_large->exists) {
                        if(settings()->get('general','image_crop')) {
                            $image->adaptiveThumb($small_width,$small_height)
                                  ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small/'.$basename)
                                  ->reload()
                                  ->adaptiveThumb($medium_width,$medium_height)
                                  ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium/'.$basename)
                                  ->reload()
                                  ->adaptiveThumb($large_width,$large_height)
                                  ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large/'.$basename)
                            ;
                        }else {
                            $image->thumb($small_width,$small_height)
                                  ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small/'.$basename)
                                  ->reload()
                                  ->thumb($medium_width,$medium_height)
                                  ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium/'.$basename)
                                  ->reload()
                                  ->thumb($large_width,$large_height)
                                  ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large/'.$basename);
                        }
                    }else {
                        if(!$thumbnail_small->exists || image($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small/'.$basename)->getWidth() !=$small_width || image($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small/'.$basename)->getHeight() != $small_height) {
                            if(settings()->get('general','image_crop')) {
                                $image->adaptiveThumb($small_width,$small_height)
                                    ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small/'.$basename);
                            }else {
                                $image->thumb($small_width,$small_height)
                                    ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small/'.$basename);
                            }
                         }
                        if(!$thumbnail_medium->exists || image($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium/'.$basename)->getWidth() !=$medium_width || image($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium/'.$basename)->getHeight() != $medium_height){
                            if(settings()->get('general','image_crop')) {
                                $image->adaptiveThumb($medium_width,$medium_height)
                                    ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium/'.$basename);
                            }else {
                                $image->thumb($medium_width,$medium_height)
                                    ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium/'.$basename);
                            }
                        }
                        if(!$thumbnail_large->exists || image($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large/'.$basename)->getWidth() !=$large_width || image($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large/'.$basename)->getHeight() != $large_height){
                            if(settings()->get('general','image_crop')) {
                                $image->adaptiveThumb($large_width,$large_height)
                                    ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large/'.$basename);
                            }else {
                                $image->thumb($large_width,$large_height)
                                    ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large/'.$basename);
                            }
                        }
                    }
                }
            }
            /*--------------------- # Xử lý ảnh thumbnail -----------------------*/
            /*--------------------- Xử lý multi categories -----------------------*/
            //$multi_categories = $_POST['Content']['multi_categories'];
            /*
             * Cần phải tìm cách tối ưu đoạn này hơn vì : $_POST['Content']['multi_categories']
             * đã là một mảng chứa id của Category rồi sao không insert ngay mảng đó vào
             * content_category_assoc với content_id vừa được tạo mà lại phải findAll
             * để lấy lại những id đó ở dạng Obj ???
             * */
            if(isset($_POST['Content']['multi_categories'])) {
                $criteria = new CDbCriteria();
                $criteria->addInCondition('id',$_POST['Content']['multi_categories']);
                $multi_categories = Category::model()->findAll($criteria);
                $model->categories = $multi_categories;
            }
            /*--------------------- # Xử lý multi categories -----------------------*/

			if(MultiModelForm::validate($media,$validatedMembers) && $model->save()){
                $masterValues = array ('content_id'=>$model->id);
                if (MultiModelForm::save($media,$validatedMembers,$deleteMembers,$masterValues)){
                    if(empty($_POST['Content']['serial'])){
                        Content::model()->updateByPk($model->getPrimaryKey(),array('serial'=>$model->getPrimaryKey()));
                    }
                    user()->setFlash('success',t('<span class="label label-success">Success</span>  Content has been created successfully','content'));
                }
                switch ($_POST['Content']['submit']) {
                    case "close":
                        $this->redirect(app()->createUrl('/content/admin'));
                        break;
                    case "new" :
                        $this->redirect(app()->createUrl('/content/create'));
                        break;
                    default :
                        $this->redirect(array('update','id'=>$model->id));
                }

            }
		}

		$this->render('create',array(
			'model'=>$model,
            'media'=>$media,
            'validatedMembers' => $validatedMembers,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
        $model=$this->loadModel($id);
        $media = new ContentMedia;
        $validatedMembers = array();  //ensure an empty array

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if(isset($_POST['Content']))
		{
            $user = getSession('current_user');
            /**
             * Fix hidden type Multiformmodel
             */
            $postMedia = $_POST['ContentMedia'];
            $refArray = $postMedia['name'];
            foreach($refArray as $key => $val) {
                if(empty($val) && empty($postMedia['url'][$key]) && empty($postMedia['description'][$key])) {
                    unset($_POST['ContentMedia']['name'][$key]);
                    unset($_POST['ContentMedia']['url'][$key]);
                    unset($_POST['ContentMedia']['description'][$key]);
                    unset($_POST['ContentMedia']['type'][$key]);
                }
            }
            $old_status = $model->status;
            /**
             * set attributes
             */
            $model->attributes=$_POST['Content'];

            /*----------------------Publishing Date-------------------------*/
            $publishing_start_date = CDateTimeParser::parse($_POST['Content']['publishing_start'],app()->locale->getDateFormat('short'));

            $publishing_start_date_time = date('Y-m-d',$publishing_start_date).' '.$_POST['Content']['publishing_start_time'];

            $publishing_end_date = CDateTimeParser::parse($_POST['Content']['publishing_end'],app()->locale->getDateFormat('short'));

            $publishing_end_date_time   = date('y-m-d',$publishing_end_date).' '.$_POST['Content']['publishing_end_time'];

            $model->publishing_start = convertTimeZone(date('Y-m-d H:i:s',strtotime($publishing_start_date_time)));

            $model->publishing_end = convertTimeZone(date('Y-m-d H:i:s',strtotime($publishing_end_date_time)));

            /*----------------------#Publishing Date-------------------------*/

            /*----------------------Xử lý Active bài viết -------------------*/
            if($old_status != 'active' && $_POST['Content']['status'] == 'active') {
                $model->activate_user_id =  $user['id'];
                $model->activate_date = new CDbExpression('UTC_TIMESTAMP()');
            }
            /*----------------------#Xử lý Active bài viết -------------------*/

            /*----------------------Serial bài viết-------------------*/
            if(isset($_POST['Content']['serial']) && is_numeric($_POST['Content']['serial'])){
                $model->serial = Content::getOriginalSerial($_POST['Content']['serial']);
            }
            /*----------------------#Serial bài viết-------------------*/

            /*--------------------- Xử lý ảnh thumbnail -----------------------*/
            $thumbnail_folder = cmsFile()->set($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/');
            $thumbnail_folder_small = cmsFile()->set($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small');
            $thumbnail_folder_medium = cmsFile()->set($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large');
            $thumbnail_folder_large = cmsFile()->set($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium');

            $post_img = $_POST['Content']['image'];
            if($post_img != '' && $model->image != $post_img) {
                $source = $_SERVER['DOCUMENT_ROOT'].$post_img;
                $file = cmsFile()->set($source);
                if($file->isfile) {
                    if(!$thumbnail_folder->exists) {
                        $thumbnail_folder->CreateDir();
                    }
                    if(!$thumbnail_folder_large->exists) {
                        $thumbnail_folder_large->CreateDir();
                    }
                    if(!$thumbnail_folder_medium->exists) {
                        $thumbnail_folder_medium->CreateDir();
                    }
                    if(!$thumbnail_folder_small->exists){
                        $thumbnail_folder_small->CreateDir();
                    }
                    $basename = $file->basename;
                    $small_width = settings()->get('general','image_thumbnail_small_width');
                    $small_height = settings()->get('general','image_thumbnail_small_height');
                    $medium_width = settings()->get('general','image_thumbnail_medium_width');
                    $medium_height = settings()->get('general','image_thumbnail_medium_height');
                    $large_width = settings()->get('general','image_thumbnail_large_width');
                    $large_height = settings()->get('general','image_thumbnail_large_height');

                    $thumbnail_small = cmsFile()->set($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small/'.$basename);
                    $thumbnail_medium = cmsFile()->set($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium/'.$basename);
                    $thumbnail_large = cmsFile()->set($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large/'.$basename);
                    $image = image($source);
                    if(!$thumbnail_small->exists && !$thumbnail_medium->exists && !$thumbnail_large->exists) {
                        if(settings()->get('general','image_crop')) {
                            $image->adaptiveThumb($small_width,$small_height)
                                ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small/'.$basename)
                                ->reload()
                                ->adaptiveThumb($medium_width,$medium_height)
                                ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium/'.$basename)
                                ->reload()
                                ->adaptiveThumb($large_width,$large_height)
                                ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large/'.$basename)
                            ;
                        }else {
                            $image->thumb($small_width,$small_height)
                                ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small/'.$basename)
                                ->reload()
                                ->thumb($medium_width,$medium_height)
                                ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium/'.$basename)
                                ->reload()
                                ->thumb($large_width,$large_height)
                                ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large/'.$basename);
                        }
                    }else {
                        if(!$thumbnail_small->exists || image($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small/'.$basename)->getWidth() !=$small_width || image($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small/'.$basename)->getHeight() != $small_height) {
                            if(settings()->get('general','image_crop')) {
                                $image->adaptiveThumb($small_width,$small_height)
                                    ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small/'.$basename);
                            }else {
                                $image->thumb($small_width,$small_height)
                                    ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/small/'.$basename);
                            }
                        }
                        if(!$thumbnail_medium->exists || image($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium/'.$basename)->getWidth() !=$medium_width || image($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium/'.$basename)->getHeight() != $medium_height){
                            if(settings()->get('general','image_crop')) {
                                $image->adaptiveThumb($medium_width,$medium_height)
                                    ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium/'.$basename);
                            }else {
                                $image->thumb($medium_width,$medium_height)
                                    ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/medium/'.$basename);
                            }
                        }
                        if(!$thumbnail_large->exists || image($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large/'.$basename)->getWidth() !=$large_width || image($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large/'.$basename)->getHeight() != $large_height){
                            if(settings()->get('general','image_crop')) {
                                $image->adaptiveThumb($large_width,$large_height)
                                    ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large/'.$basename);
                            }else {
                                $image->thumb($large_width,$large_height)
                                    ->save($_SERVER['DOCUMENT_ROOT'].'/resources/thumbnail/large/'.$basename);
                            }
                        }
                    }
                }
            }
            /*--------------------- # Xử lý ảnh thumbnail -----------------------*/

            /*--------------------- Xử lý multi categories -----------------------*/
            //$multi_categories = $_POST['Content']['multi_categories'];
            /*
             * Cần phải tìm cách tối ưu đoạn này hơn vì : $_POST['Content']['multi_categories']
             * đã là một mảng chứa id của Category rồi sao không insert ngay mảng đó vào
             * content_category_assoc với content_id vừa được tạo mà lại phải findAll
             * để lấy lại những id đó ở dạng Obj ???
             * */
            if(isset($_POST['Content']['multi_categories'])) {
                $criteria = new CDbCriteria();
                $criteria->addInCondition('id',$_POST['Content']['multi_categories']);
                $multi_categories = Category::model()->findAll($criteria);
                $model->categories = $multi_categories;
            }
            /*--------------------- # Xử lý multi categories -----------------------*/
            $masterValues = array ('content_id'=>$model->id);
            if( //Save the master model after saving valid members
                MultiModelForm::save($media,$validatedMembers,$deleteMembers,$masterValues) &&
                $model->save()
            )
                user()->setFlash('success',t('<span class="label label-success">Success</span>  Content has been updated successfully','content'));
                $this->redirect(url('/content/update',array('id'=>$model->id)));
		} // End POST

        /************************************/
        $model->multi_categories = $model->categories;

        /********************** Xử lý hiển thị ngày tháng ************************/
        $format_date = locale()->getDateFormat('short');
        if(timeFormat24()) {
            $format_time = 'H:i';
        } else {
            $format_time = 'h:i A';
        }
        if($model->publishing_start != '0000-00-00 00:00:00' && $model->publishing_start != '' && $model->publishing_start != null) {
            $ps_timestamp = strtotime(convertTimeZone($model->publishing_start,'UTC',app()->timeZone));
            $model->publishing_start = app()->dateFormatter->format($format_date,$ps_timestamp);
            $model->publishing_start_time = date($format_time,$ps_timestamp);
        }else {
            $model->publishing_start = '';
            $model->publishing_start_time = '';
        }
        if($model->publishing_end != '0000-00-00 00:00:00' && $model->publishing_end != '' && $model->publishing_end != null) {
            $pe_timestamp = strtotime(convertTimeZone($model->publishing_end,'UTC',app()->timeZone));
            $model->publishing_end = app()->dateFormatter->format($format_date,$pe_timestamp);
            $model->publishing_end_time = date($format_time,$pe_timestamp);
        }else {
            $model->publishing_end = '';
            $model->publishing_end_time = '';
        }
        /********************** #Xử lý ngày tháng ************************/
        $this->render('update',array(
            'model'=>$model,
            'media'=>$media,
            'validatedMembers' => $validatedMembers,
        ));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
            $content = $this->loadModel($id);
            if($content->id == $content->serial) {
                $serial_replace = Content::model()->find('serial=:serial && id!=:id',array(':serial'=>$content->id,':id'=>$content->id));
                if(!empty($serial_replace)) {
                    $update_serial = Content::model()->updateAll(array('serial'=>$serial_replace->id),'serial=:serial',array(':serial'=>$content->id));
                    if($update_serial) {
                        $delete = $content->delete();
                    }
                }else {
                    $delete = $content->delete();
                }
            } else {
                $delete = $content->delete();
            }
            if($delete == true) {

            }
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

    /**
     *  Batch Switch Status
     */
    public function actionBatchSwitchStatus() {
        $request = app()->request;
        if($request->isPostRequest) {
            $type = $request->getPost('type');
            $types = array(
              'active','inactive','deleted'
            );
            if(in_array($type,$types)) {
                $user = getSession('current_user');
                $ids = explode(',',$request->getPost('ids'));
                foreach($ids as $id){
                    $model = Content::model()->findByPk($id,'status != :status',array(':status'=>$type));
                   if(!empty($model)){
                       $model->status = $type;
                       if($type == 'active') {
                           $model->activate_date = new CDbExpression('UTC_TIMESTAMP()');
                           $model->activate_user_id = $user['id'];
                       }else {
                           $model->activate_date = '0000-00-00 00:00:00';
                       }
                       $model->save();
                   }
                }
            } else
                throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
        } else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     *  Batch Delete
     */
    public function actionBatchDelete() {
        $request = app()->request;
        if($request->isPostRequest) {
            $ids = explode(',',$request->getPost('ids'));
            foreach($ids as $id) {
                $content = $this->loadModel($id);
                if($content->id == $content->serial) {
                    $serial_replace = Content::model()->find('serial=:serial && id!=:id',array(':serial'=>$content->id,':id'=>$content->id));
                    if(!empty($serial_replace)) {
                        $update_serial = Content::model()->updateAll(array('serial'=>$serial_replace->id),'serial=:serial',array(':serial'=>$content->id));
                        if($update_serial) {
                            $content->delete();
                        }
                    }else {
                        $content->delete();
                    }
                } else {
                    $content->delete();
                }
            }
        } else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{

		$model=new Content('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Content']))
			$model->attributes=$_GET['Content'];
		$this->render('admin',array(
			'model'=>$model,
		));
	}
    /**
     * For all editable
     *
     */
    public function actionEditable () {
        $ed = new TbEditableSaver("Content");
        $ed->onBeforeUpdate = function($event) {
            $value = Yii::app()->request->getParam('value');
            if($event->sender->attribute == 'status' && $value == 'active') {
                $event->sender->setAttribute('activate_date', new CDbExpression('UTC_TIMESTAMP()'));
            }
        };
        $ed->update();
    }
    /*
     * Relational
     */
    public function actionRelational()
    {
        $id = Yii::app()->getRequest()->getParam('id');
        $model = Content::model()->findByPk($id);
        $this->renderPartial('_relational', array(
            'model'=>$model
        ));
    }
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Content::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='content-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
